<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 测试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            font-weight: bold;
        }
        .connected {
            background: #d4edda;
            color: #155724;
        }
        .disconnected {
            background: #f8d7da;
            color: #721c24;
        }
        .connecting {
            background: #fff3cd;
            color: #856404;
        }
        .controls {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            background: #4CAF50;
            color: white;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background: #45a049;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        #messages {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            height: 300px;
            overflow-y: auto;
            background: #fafafa;
            margin: 20px 0;
        }
        .message {
            padding: 8px;
            margin: 5px 0;
            border-left: 3px solid #4CAF50;
            background: white;
            border-radius: 3px;
        }
        .message.sent {
            border-left-color: #2196F3;
        }
        .message.error {
            border-left-color: #f44336;
            background: #ffebee;
        }
        .message .time {
            color: #999;
            font-size: 12px;
            margin-right: 10px;
        }
        input[type="text"] {
            padding: 10px;
            width: 70%;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin: 20px 0;
        }
        .stat-card {
            padding: 15px;
            background: #f0f0f0;
            border-radius: 5px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #4CAF50;
        }
        .stat-label {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔌 WebSocket 测试页面</h1>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-value" id="messageCount">0</div>
                <div class="stat-label">消息数量</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="connectionTime">0s</div>
                <div class="stat-label">连接时长</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="pingTime">-</div>
                <div class="stat-label">延迟(ms)</div>
            </div>
        </div>

        <div class="controls">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开</button>
            <button onclick="sendPing()">Ping</button>
            <button onclick="joinRoom()">加入房间</button>
            <button onclick="leaveRoom()">离开房间</button>
            <button onclick="clearMessages()">清空消息</button>
        </div>

        <div>
            <input type="text" id="messageInput" placeholder="输入消息内容..." onkeypress="handleEnter(event)">
            <button onclick="sendMessage()">发送</button>
        </div>

        <div id="messages"></div>
    </div>

    <script>
        let ws = null;
        let messageCount = 0;
        let connectionStartTime = null;
        let connectionTimer = null;
        let pingStartTime = null;

        function updateStatus(status, text) {
            const statusEl = document.getElementById('status');
            statusEl.className = 'status ' + status;
            statusEl.textContent = text;
        }

        function connect() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                addMessage('已经连接', 'error');
                return;
            }

            updateStatus('connecting', '连接中...');
            
            // 生成随机用户ID
            const userId = 'user_' + Math.random().toString(36).substr(2, 9);
            const wsUrl = `ws://localhost:8087/ws/connect?user_id=${userId}&role=user`;
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                updateStatus('connected', '已连接 - 用户ID: ' + userId);
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                
                connectionStartTime = Date.now();
                startConnectionTimer();
                
                addMessage('WebSocket 连接成功', 'system');
            };
            
            ws.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    handleMessage(data);
                } catch (e) {
                    addMessage('收到消息: ' + event.data);
                }
                
                messageCount++;
                document.getElementById('messageCount').textContent = messageCount;
            };
            
            ws.onerror = function(error) {
                addMessage('连接错误: ' + error, 'error');
                updateStatus('disconnected', '连接错误');
            };
            
            ws.onclose = function() {
                updateStatus('disconnected', '未连接');
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
                stopConnectionTimer();
                addMessage('连接已断开', 'system');
            };
        }

        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接 WebSocket', 'error');
                return;
            }
            
            const data = {
                type: 'chat',
                event: 'chat',
                data: {
                    message: message,
                    timestamp: Date.now()
                }
            };
            
            ws.send(JSON.stringify(data));
            addMessage('发送: ' + message, 'sent');
            input.value = '';
        }

        function sendPing() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接 WebSocket', 'error');
                return;
            }
            
            pingStartTime = Date.now();
            
            const data = {
                type: 'system',
                event: 'ping',
                data: 'ping'
            };
            
            ws.send(JSON.stringify(data));
            addMessage('发送 Ping', 'sent');
        }

        function joinRoom() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接 WebSocket', 'error');
                return;
            }
            
            const data = {
                type: 'system',
                event: 'join_room',
                data: 'test_room'
            };
            
            ws.send(JSON.stringify(data));
            addMessage('请求加入房间: test_room', 'sent');
        }

        function leaveRoom() {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                addMessage('请先连接 WebSocket', 'error');
                return;
            }
            
            const data = {
                type: 'system',
                event: 'leave_room',
                data: 'test_room'
            };
            
            ws.send(JSON.stringify(data));
            addMessage('请求离开房间: test_room', 'sent');
        }

        function handleMessage(data) {
            if (data.event === 'pong' && pingStartTime) {
                const pingTime = Date.now() - pingStartTime;
                document.getElementById('pingTime').textContent = pingTime;
                addMessage('收到 Pong - 延迟: ' + pingTime + 'ms');
                pingStartTime = null;
            } else if (data.event === 'welcome') {
                addMessage('欢迎消息: ' + JSON.stringify(data.data));
            } else if (data.event === 'room_joined') {
                addMessage('已加入房间: ' + data.data.room);
            } else if (data.event === 'room_left') {
                addMessage('已离开房间: ' + data.data.room);
            } else {
                addMessage('收到消息: ' + JSON.stringify(data));
            }
        }

        function addMessage(text, type = '') {
            const messagesEl = document.getElementById('messages');
            const messageEl = document.createElement('div');
            messageEl.className = 'message ' + type;
            
            const time = new Date().toLocaleTimeString();
            messageEl.innerHTML = `<span class="time">${time}</span>${text}`;
            
            messagesEl.appendChild(messageEl);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            messageCount = 0;
            document.getElementById('messageCount').textContent = '0';
        }

        function handleEnter(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function startConnectionTimer() {
            connectionTimer = setInterval(() => {
                if (connectionStartTime) {
                    const seconds = Math.floor((Date.now() - connectionStartTime) / 1000);
                    document.getElementById('connectionTime').textContent = seconds + 's';
                }
            }, 1000);
        }

        function stopConnectionTimer() {
            if (connectionTimer) {
                clearInterval(connectionTimer);
                connectionTimer = null;
            }
            document.getElementById('connectionTime').textContent = '0s';
        }

        // 页面加载完成后自动连接
        window.onload = function() {
            // connect();
        };

        // 页面关闭时断开连接
        window.onbeforeunload = function() {
            if (ws) {
                ws.close();
            }
        };
    </script>
</body>
</html>